// components/list-picker/index.ts
const app = getApp()
Component({
  properties: {
    title: {
      type: String,
      value: '选择'
    },
    list: {
      type: Array,
      value: [],
      observer(newVal) {
        if (JSON.stringify(newVal) === JSON.stringify(this.data.originalList)) return;
        this.setData({
          originalList: newVal.map(item => ({ ...item })),
          keyword: ''
        });
        this._debounceFilter();
      }
    },
    type: {
      type: String,
      value: 'single'
    },
    addLink: {
      type: String,
      value: ''
    }
  },

  data: {
    drawer: null,
    keyword: '',
    originalList: [],
    filteredList: [] // 新增字段存储过滤结果
  },

  lifetimes: {
    attached() {
      this.setData({
        drawer: this.selectComponent('#v-drawer'),
        originalList: this.properties.list.map(item => ({ ...item })),
        filteredList: this.properties.list // 初始化时显示完整列表
      });
    }
  },

  methods: {
    togglePicker() {
      this.data.drawer.toggleDrawer();
    },

    handleAdd() {
      const addLink = this.data.addLink
      this.togglePicker();
      if (addLink && addLink.length > 0) {
        app.navigateTo(addLink)
      }
    },

    handleSelectItem(e) {
      const id = e.currentTarget.dataset.id;
      const type = this.data.type;
      const originalList = this.data.originalList.map(item => ({ ...item }));
      const index = originalList.findIndex(item => item.id === id);

      if (index === -1) return;

      if (type === 'single') {
        originalList.forEach(item => item.selected = item.id === id);
      } else {
        originalList[index].selected = !originalList[index].selected;
      }

      this.setData({ originalList }, () => this.filter());
    },

    handleSelectConfirm() {
      const selectedItems = this.data.originalList.filter(item => item.selected);
      this.triggerEvent('confirm', { selectedItems });
      this.togglePicker();
    },

    _debounceFilter() {
      clearTimeout(this.filterTimer);
      this.filterTimer = setTimeout(() => this.filter(), 300);
    },

    filter(e) {
      const keyword = (e ? e.detail.value : this.data.keyword).trim().toLowerCase();
      this.setData({ keyword });

      const filteredList = this.data.originalList.filter(item => {
        const text = (item.name || item.title || '').toLowerCase();
        return text.includes(keyword);
      });

      this.setData({ filteredList }); // 更新过滤结果
    }
  }
});